import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'dart:io';

class NotificationService extends GetxService {
  final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  
  bool _isInitialized = false;
  bool get isInitialized => _isInitialized;
  
  @override
  Future<void> onInit() async {
    super.onInit();
    await _initializeNotifications();
  }
  
  Future<void> _initializeNotifications() async {
    try {
      // Android 初始化设置
      const AndroidInitializationSettings initializationSettingsAndroid =
          AndroidInitializationSettings('@mipmap/ic_launcher');
      
      // iOS 初始化设置
      const DarwinInitializationSettings initializationSettingsIOS =
          DarwinInitializationSettings(
        requestAlertPermission: true,
        requestBadgePermission: true,
        requestSoundPermission: true,
      );
      
      const InitializationSettings initializationSettings =
          InitializationSettings(
        android: initializationSettingsAndroid,
        iOS: initializationSettingsIOS,
      );
      
      await _flutterLocalNotificationsPlugin.initialize(
        initializationSettings,
        onDidReceiveNotificationResponse: _onNotificationTapped,
      );
      
      // 请求权限
      await _requestPermissions();
      
      _isInitialized = true;
    } catch (e) {
      print('通知服务初始化失败: $e');
    }
  }
  
  Future<void> _requestPermissions() async {
    if (Platform.isAndroid) {
      final AndroidFlutterLocalNotificationsPlugin? androidImplementation =
          _flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>();
      
      await androidImplementation?.requestNotificationsPermission();
    } else if (Platform.isIOS) {
      final IOSFlutterLocalNotificationsPlugin? iosImplementation =
          _flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
              IOSFlutterLocalNotificationsPlugin>();
      
      await iosImplementation?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
    }
  }
  
  void _onNotificationTapped(NotificationResponse notificationResponse) {
    final payload = notificationResponse.payload;
    if (payload != null) {
      // 处理通知点击事件
      _handleNotificationTap(payload);
    }
  }
  
  void _handleNotificationTap(String payload) {
    try {
      // 根据payload跳转到相应页面
      if (payload.startsWith('upload:')) {
        Get.toNamed('/upload');
      } else if (payload.startsWith('download:')) {
        Get.toNamed('/download');
      } else if (payload.startsWith('sync:')) {
        Get.toNamed('/home');
      }
    } catch (e) {
      print('处理通知点击失败: $e');
    }
  }
  
  // 显示简单通知
  Future<void> showNotification({
    required int id,
    required String title,
    required String body,
    String? payload,
  }) async {
    if (!_isInitialized) return;
    
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
      'snail_netdisk_channel',
      '蜗牛网盘',
      channelDescription: '蜗牛网盘通知',
      importance: Importance.defaultImportance,
      priority: Priority.defaultPriority,
      showWhen: true,
    );
    
    const DarwinNotificationDetails iOSPlatformChannelSpecifics =
        DarwinNotificationDetails();
    
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
    );
    
    await _flutterLocalNotificationsPlugin.show(
      id,
      title,
      body,
      platformChannelSpecifics,
      payload: payload,
    );
  }
  
  // 显示进度通知
  Future<void> showProgressNotification({
    required int id,
    required String title,
    required String body,
    required int progress,
    required int maxProgress,
    String? payload,
  }) async {
    if (!_isInitialized) return;
    
    final AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
      'snail_netdisk_progress_channel',
      '蜗牛网盘进度',
      channelDescription: '文件传输进度通知',
      importance: Importance.low,
      priority: Priority.low,
      showWhen: false,
      onlyAlertOnce: true,
      showProgress: true,
      maxProgress: maxProgress,
      progress: progress,
      indeterminate: false,
    );
    
    const DarwinNotificationDetails iOSPlatformChannelSpecifics =
        DarwinNotificationDetails();
    
    final NotificationDetails platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
    );
    
    await _flutterLocalNotificationsPlugin.show(
      id,
      title,
      body,
      platformChannelSpecifics,
      payload: payload,
    );
  }
  
  // 显示不确定进度通知
  Future<void> showIndeterminateProgressNotification({
    required int id,
    required String title,
    required String body,
    String? payload,
  }) async {
    if (!_isInitialized) return;
    
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
      'snail_netdisk_progress_channel',
      '蜗牛网盘进度',
      channelDescription: '文件传输进度通知',
      importance: Importance.low,
      priority: Priority.low,
      showWhen: false,
      onlyAlertOnce: true,
      showProgress: true,
      indeterminate: true,
    );
    
    const DarwinNotificationDetails iOSPlatformChannelSpecifics =
        DarwinNotificationDetails();
    
    final NotificationDetails platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
    );
    
    await _flutterLocalNotificationsPlugin.show(
      id,
      title,
      body,
      platformChannelSpecifics,
      payload: payload,
    );
  }
  
  // 上传通知
  Future<void> showUploadStartNotification(String fileName) async {
    await showNotification(
      id: 1001,
      title: '开始上传',
      body: '正在上传文件: $fileName',
      payload: 'upload:start',
    );
  }
  
  Future<void> showUploadProgressNotification(
    String fileName,
    int progress,
    int total,
  ) async {
    await showProgressNotification(
      id: 1001,
      title: '上传中',
      body: '正在上传: $fileName',
      progress: progress,
      maxProgress: total,
      payload: 'upload:progress',
    );
  }
  
  Future<void> showUploadCompleteNotification(String fileName) async {
    await showNotification(
      id: 1002,
      title: '上传完成',
      body: '文件上传成功: $fileName',
      payload: 'upload:complete',
    );
  }
  
  Future<void> showUploadFailedNotification(String fileName, String error) async {
    await showNotification(
      id: 1003,
      title: '上传失败',
      body: '文件上传失败: $fileName\n错误: $error',
      payload: 'upload:failed',
    );
  }
  
  // 下载通知
  Future<void> showDownloadStartNotification(String fileName) async {
    await showNotification(
      id: 2001,
      title: '开始下载',
      body: '正在下载文件: $fileName',
      payload: 'download:start',
    );
  }
  
  Future<void> showDownloadProgressNotification(
    String fileName,
    int progress,
    int total,
  ) async {
    await showProgressNotification(
      id: 2001,
      title: '下载中',
      body: '正在下载: $fileName',
      progress: progress,
      maxProgress: total,
      payload: 'download:progress',
    );
  }
  
  Future<void> showDownloadCompleteNotification(String fileName) async {
    await showNotification(
      id: 2002,
      title: '下载完成',
      body: '文件下载成功: $fileName',
      payload: 'download:complete',
    );
  }
  
  Future<void> showDownloadFailedNotification(String fileName, String error) async {
    await showNotification(
      id: 2003,
      title: '下载失败',
      body: '文件下载失败: $fileName\n错误: $error',
      payload: 'download:failed',
    );
  }
  
  // 同步通知
  Future<void> showSyncStartNotification() async {
    await showIndeterminateProgressNotification(
      id: 3001,
      title: '同步中',
      body: '正在同步云端文件...',
      payload: 'sync:start',
    );
  }
  
  Future<void> showSyncCompleteNotification(int fileCount) async {
    await showNotification(
      id: 3002,
      title: '同步完成',
      body: '已同步 $fileCount 个文件',
      payload: 'sync:complete',
    );
  }
  
  Future<void> showSyncFailedNotification(String error) async {
    await showNotification(
      id: 3003,
      title: '同步失败',
      body: '同步失败: $error',
      payload: 'sync:failed',
    );
  }
  
  // 登录通知
  Future<void> showLoginSuccessNotification() async {
    await showNotification(
      id: 4001,
      title: '登录成功',
      body: '已成功登录天翼云盘',
      payload: 'login:success',
    );
  }
  
  Future<void> showLoginFailedNotification(String error) async {
    await showNotification(
      id: 4002,
      title: '登录失败',
      body: '登录失败: $error',
      payload: 'login:failed',
    );
  }
  
  Future<void> showSessionExpiredNotification() async {
    await showNotification(
      id: 4003,
      title: '会话过期',
      body: '登录会话已过期，请重新登录',
      payload: 'login:expired',
    );
  }
  
  // 取消通知
  Future<void> cancelNotification(int id) async {
    await _flutterLocalNotificationsPlugin.cancel(id);
  }
  
  // 取消所有通知
  Future<void> cancelAllNotifications() async {
    await _flutterLocalNotificationsPlugin.cancelAll();
  }
  
  // 取消上传通知
  Future<void> cancelUploadNotifications() async {
    await cancelNotification(1001);
    await cancelNotification(1002);
    await cancelNotification(1003);
  }
  
  // 取消下载通知
  Future<void> cancelDownloadNotifications() async {
    await cancelNotification(2001);
    await cancelNotification(2002);
    await cancelNotification(2003);
  }
  
  // 取消同步通知
  Future<void> cancelSyncNotifications() async {
    await cancelNotification(3001);
    await cancelNotification(3002);
    await cancelNotification(3003);
  }
}